<?php
/**
 * TP5版本workerman
 * */
namespace app\push\controller;

use think\Db;
use think\worker\Server;
use Workerman\Lib\Timer;

class Worker extends Server
{
	protected $socket = 'websocket://worker.lizaonet.com:2346';
	protected $uidConnections = [];
	protected $HEARTBEAT_TIME = '15';

	public function onMessageSwitch($connection, $data)
	{
		switch ($data['type']) {
			case 'user_connect':
				//用户连接成功
				$user_id = $data['user_id'];

				$username = Db::name('user')->where(['id' => $user_id])->value('username');

				$data = [
					'type' => 'contact',
					'msg' => $username . '，请问你有什么问题呢？'
				];
				$connection->send(json_encode($data, JSON_UNESCAPED_UNICODE));
				break;
			case 'user_send':
				$data = [
					'type' => 'me',
					'msg' => $data['msg']
				];
				$connection->send(json_encode($data, JSON_UNESCAPED_UNICODE));
				break;
			case 'heartbeat';
				$data = [
					'type' => 'heartbeat',
					'msg' => '心跳'
				];
				$connection->send(json_encode($data, JSON_UNESCAPED_UNICODE));
				break;
			default:
				$connection->send('默认消息');
				break;
		}
	}

	/**
	 * 收到信息
	 * @param $connection
	 * @param $data
	 */
	public function onMessage($connection, $data)
	{
		$connection->lastMessageTime = time();
		$data = json_decode($data, true);
		file_put_contents(RUNTIME_PATH . 'onMessage.txt', json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);

		$this->onMessageSwitch($connection, $data);
	}

	/**
	 * 当连接建立时触发的回调函数
	 * @param $connection
	 */
	public function onConnect($connection)
	{
		$connection->send('连接建立');
	}

	/**
	 * 当连接断开时触发的回调函数
	 * @param $connection
	 */
	public function onClose($connection)
	{

	}

	/**
	 * 当客户端的连接上发生错误时触发
	 * @param $connection
	 * @param $code
	 * @param $msg
	 */
	public function onError($connection, $code, $msg)
	{
		echo "error $code $msg\n";
	}

	/**
	 * 每个进程启动
	 * @param $worker
	 */
	public function onWorkerStart($worker)
	{
		// 开启一个内部端口，方便内部系统推送数据，Text协议格式 文本+换行符
		$inner_text_worker = new \Workerman\Worker('Text://127.0.0.1:5678');
		$inner_text_worker->onMessage = function ($connection, $buffer) {
			$buffer = json_decode($buffer, false);
			$this->onMessageSwitch($connection, $buffer);
		};
		$inner_text_worker->listen();
		Timer::add(
			5, function () use ($worker) {
			$time_now = time();
			foreach ($worker->connections as $connection) {
				// 有可能该connection还没收到过消息，则lastMessageTime设置为当前时间
				if (empty($connection->lastMessageTime)) {
					$connection->lastMessageTime = $time_now;
					continue;
				}
				$diff_time = $time_now - $connection->lastMessageTime;
//				$msg = '距离上次通话已经过去' . $diff_time . '秒';
//				$connection->send($msg);
				// 上次通讯时间间隔大于心跳间隔，则认为客户端已经下线，关闭连接
				if ($diff_time > $this->HEARTBEAT_TIME) {
					$close_data = [
						'type' => 'close',
						'msg' => '连接断开' . $connection->id
					];
					$connection->send(json_encode($close_data, JSON_UNESCAPED_UNICODE));
					$connection->close();
				}else{
					$connection->send('距离上次通话已经过去' . $diff_time . '秒');
				}
			}
		}
		);
	}

	public function sendUid($uid, $message)
	{
		if (isset($this->uidConnections[$uid])) {
			// 获取之前用户的链接
			$conn = $this->uidConnections[$uid];
			//echo $uid.PHP_EOL;
			$conn->send($message);

			return true;
		}

		return false;
	}

	public function sendAll($message, $uid = '')
	{
		foreach ($this->uidConnections as $conn) {
			if (!empty($uid)) {
				//不推送给自己
				if ($conn != $this->uidConnections[$uid]) {
					$conn->send($message);
				}
			} else {
				$conn->send($message);
			}
		}

		return true;
	}
}
